class Solution {
public:
    int longestValidParentheses(string s) {
        int ma = 0;
        vector<int> sta;
        sta.push_back(-1);
        for(int i = 0;i < s.size();i++){
            if(s[i] == '(')sta.push_back(i);
            else{
                sta.pop_back();
                if(sta.empty())sta.push_back(i);
                else ma = max(ma,i - sta.back());
            }
        }

        return ma;
    }
};
